<template>
  <span v-if="props.showText">{{ message }}</span>
  <el-checkbox-group
    v-else
    v-model="dicSelect"
    @change="handleChange"
  >
    <el-checkbox
      v-for="item in options" 
      :key="item.key"
      :label="item.key"
    >{{item.value}}</el-checkbox>
  </el-checkbox-group>
</template>


<script setup>
import {ref, watch, onUnmounted, onMounted} from 'vue';
import {useDictionaryStore} from '@/pinia/modules/dictionary';
import {emitter} from "@/utils/bus";

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  dicCode: String,
  options: {
    type: Array,
    default: () => []
  },
  showText: Boolean
});

const dictionaryStore = useDictionaryStore();
const options = ref([]);
const dicSelect = ref([]);
const message = ref();

const handleChange = (event) => {
  emit('update:modelValue', dicSelect.value && dicSelect.value.length > 0 ? dicSelect.value.join(',') : '');
  emit('change', event);
};

const loadDicAndShow = async(dicCode) => {
  if ((dicCode || '') === '') {
    options.value = [];
  } else {
    options.value = await dictionaryStore.getDictionary(dicCode);
  }

  calcValue();
};

const calcValue = () => {
  message.value = '';
  if (options.value && options.value.length > 0) {
    message.value = '';
    let option = options.value.filter(item => dicSelect.value.indexOf(item.key) >= 0)
    if (option.length > 0) {
      option.forEach(item => {
        if (message.value.length > 0) {
          message.value += '，' + item.value;
        } else {
          message.value = item.value;
        }
      });
    } else {
      message.value = props.modelValue;
    }
  } else {
    message.value = props.modelValue;
  }
};

const init = (data) => {
  dicSelect.value = data && data.modelValue ? data.modelValue.split(',') : [];
  if (data.options && data.options.length > 0) {
    options.value = data.options;
    calcValue();
  } else if (data.dicCode) {
    loadDicAndShow(data.dicCode);
    emitter.off('dictionary.change');
    emitter.on('dictionary.change', () => {
      loadDicAndShow(data.dicCode);
    });
  }
};

watch(() => props, (data) => {
  init(data);
}, {deep: true});

onMounted(() => {
  dicSelect.value = props.modelValue ? props.modelValue.split(',') : [];
  if (props.options && props.options.length > 0) {
    options.value = props.options;
    calcValue();
  } else if (props.dicCode) {
    loadDicAndShow(props.dicCode);
    emitter.on('dictionary.change', () => {
      loadDicAndShow(props.dicCode);
    });
  }
});

onUnmounted(() => {
  emitter.off('dictionary.change');
});
</script>